import Vue from 'vue'
import router from './router'
import store from './store'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
// import { getToken } from '@/utils/auth' // get token from cookie
import getPageTitle from '@/utils/get-page-title'
import { generateRegistry } from '@/registerApps'
// 需要在首次生成qiankun的时候将内部维护插件注入，以实现业务组件分离效果
import { whiteList } from './whiteList'
NProgress.configure({ showSpinner: false }) // NProgress Configuration

router.beforeEach(async(to, from, next) => {
  // start progress bar
  NProgress.start()
  // 这一段是为了处理多标签页时在一个账户登出，切换到另一个账户点击路由从而导致权限失控的问题
  if (
    Vue.prototype.$userInfo.userRep.username !==
    localStorage.getItem('username')
  ) {
    localStorage.removeItem('vuex')
    store.commit('sys/SET_MENU', [])
    store.commit('sys/SET_PATH_LIST', [])
    window.location.reload()
  }
  if (store.state.sys.pathList.length === 0) {
    // 没有菜单
    await store.dispatch('sys/getMenu', true)
    await store.dispatch('sys/getAuth')
    // 在下一个周期里才能拿到目前默认跳转的路由
    Vue.nextTick(() => {
      generateRegistry(store.state.sys.originData, store._vm)
    })
    next(to.path)
    return
  }
  // 如果有历史数据则再注册一遍子应用
  if (store.state.sys.originData.length > 0 && !store.state.sys.regStatue) {
    generateRegistry(store.state.sys.originData, store._vm)
  }

  // 如果是第一遍注冊路由則不需要進入404
  if (
    store.state.sys.pathList.length > 0 &&
    !whiteList.includes(to.path) &&
    !store.state.sys.pathList.includes(to.path) &&
    to.path !== '/404' &&
    !store.state.sys.regStatue
  ) {
    // console.log(store.state.sys.pathList, 'pathList')
    // Message.error('用户无权限')
    await store.dispatch('sys/getMenu')
    await store.dispatch('sys/getAuth')
    if (to.path === '/report') {
      next()
      NProgress.done()
    } else {
      next({ path: '/404' })
      NProgress.done()
    }
  } else {
    // set page title
    const menu = store.state.sys.allMenu.filter(v => {
      return v.resUrl === to.path
    })[0]
    document.title = menu ? '生产管控-' + menu.name : '生产管控'
    next()
  }
})

router.afterEach(() => {
  // finish progress bar
  NProgress.done()
})
